package com.yunqi.autovender.view;

import android.app.Dialog;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;

import com.yunqi.autovender.R;
import com.yunqi.autovender.databinding.DialogStackModifyBinding;
import com.yunqi.autovender.model.StackInfo;

import google.architecture.common.util.ToastUtils;
import google.architecture.coremodel.callback.ConfirmCallback;
import google.architecture.coremodel.callback.StackModifyCallback;
import google.architecture.coremodel.datamodel.http.entities.BaseData;
import google.architecture.coremodel.datamodel.http.entities.ProductData;
import google.architecture.coremodel.datamodel.http.repository.AutoVenderDataRepository;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 库存修改Dialog
 */
public class StackModifyDialog extends Dialog {
    protected String TAG = this.getClass().getName();
    private final static int MAX_STACK = 100;//最大库存数量
    private final static int MIN_STACK = 1;//最小库存数量
    private Context mContext;
    private ProductData.Product mProduct;
    private StackInfo mStackInfo = new StackInfo();
    private AutoVenderDataRepository mRepository;
    private DialogStackModifyBinding mBinding;
    private final CompositeDisposable mDisposable = new CompositeDisposable();
    private ModifyInterface mInterface;

    public StackModifyDialog(@NonNull Context context, @NonNull ProductData.Product product) {
        this(context, R.style.MyDialog);
        mContext = context;
        mProduct = product;
        mStackInfo.count.set(product.getDrugQuantity());
        mStackInfo.addEnable.set(product.getDrugQuantity() < MAX_STACK);
        mStackInfo.reduceEnable.set(product.getDrugQuantity() > MIN_STACK);
        mStackInfo.hasModify.set(false);
        mRepository = new AutoVenderDataRepository(context);
    }


    public void setModifyInterface(ModifyInterface modifyInterface) {
        mInterface = modifyInterface;
    }

    private StackModifyDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = View.inflate(mContext, R.layout.dialog_stack_modify, null);
        mBinding = DataBindingUtil.bind(view);
        setContentView(view);
        mBinding.setCallback(mStackModifyCallback);
        mBinding.setProductItem(mProduct);
        mBinding.setStackInfo(mStackInfo);
        setCanceledOnTouchOutside(true);
        hideLoading();
    }

    private StackModifyCallback mStackModifyCallback = new StackModifyCallback() {

        @Override
        public void onAdd() {
            Integer count = mStackInfo.count.get();
            count++;
            mStackInfo.count.set(count);
            mStackInfo.addEnable.set(count < MAX_STACK);
            mStackInfo.reduceEnable.set(true);
            mStackInfo.hasModify.set(count != mProduct.getDrugQuantity());
        }

        @Override
        public void onReduce() {
            Integer count = mStackInfo.count.get();
            count--;
            mStackInfo.count.set(count);
            mStackInfo.addEnable.set(count < MAX_STACK);
            mStackInfo.reduceEnable.set(count > MIN_STACK);
            mStackInfo.hasModify.set(count != mProduct.getDrugQuantity());
        }

        @Override
        public void onClick(int action) {
            switch (action) {
                case ConfirmCallback.ACTION_CANCEL:
                    dismiss();
                    break;
                case ConfirmCallback.ACTION_CONFIRM:
                    showLoading();
                    addDrug();
                    break;
            }
        }
    };

    @Override
    public void dismiss() {
        super.dismiss();
        mDisposable.clear();
        mInterface = null;
    }

    public void hideLoading() {
        mBinding.layoutLoading.setVisibility(View.GONE);
    }

    private void showLoading() {
        mBinding.layoutLoading.setVisibility(View.VISIBLE);
    }


    private void addDrug() {
        int operNum = mStackInfo.count.get() - mProduct.getDrugQuantity();
        mRepository.addDrug(mProduct.getPlanId(), mProduct.getDrugQuantity(), operNum)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseData value) {
                        if (value.getCode() == 200) {
                            Log.d(TAG, "修改库存成功！");
                            ToastUtils.showShortToast("修改库存成功!");
                            if (mInterface != null)
                                mInterface.onModifyCount(mStackInfo.count.get());
                        } else {
                            Log.e(TAG, "错误信息code：" + value.getCode() + ",message:" + value.getMessage());
                            ToastUtils.showShortToast("修改库存失败!");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismiss();
                        Log.e(TAG, "onError------>" + e.getMessage());
                        ToastUtils.showShortToast("连接服务器异常，请检查网络！");
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        dismiss();
                        Log.i(TAG, "onComplete------>");
                    }
                });
    }


    public interface ModifyInterface {
        /**
         * 修改后的库存回调接口
         * @param count
         */
        void onModifyCount(int count);
    }
}
